package command.client;

import client.ClientSession;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.MessageCommunication;
import model.User;

public class LoginUserClient implements CommandClient {

    private User user;
    private MessageCommunication operationStatus;

    public LoginUserClient() {
    }

    public void setUserLogin(User u) {
        user = u;
    }

    public User getUserLogin() {
        return user;
    }

    public MessageCommunication getOperationStatus() {
        return operationStatus;
    }

    @Override
    public void execute(ClientSession clientSession, boolean isInvokedByTheServer) {
        try {
            clientSession.getObjectOutputStream().writeObject(new MessageCommunication(null, "loginuserserver"));
            clientSession.getObjectOutputStream().flush();
            clientSession.getObjectOutputStream().writeObject(user);
            clientSession.getObjectOutputStream().flush();
            operationStatus = (MessageCommunication) clientSession.getObjectInputStream().readObject();
            if (operationStatus != null) {
                if (operationStatus.getStatus()) {
                    user = (User) clientSession.getObjectInputStream().readObject();
                    clientSession.setUserSession(user);
                }
            }
        } catch (ClassNotFoundException | IOException ex) {
            Logger.getLogger(LoginUserClient.class.getName()).log(Level.SEVERE,
                    "Fallo al realizar el login del usuario en el cliente", ex);
        }
    }
}
